import router from './index.ts'
import { useUserStore } from '@/store/modules/user.ts'
import 'nprogress/nprogress.css'
import nprogress from 'nprogress'
import { ElMessage } from 'element-plus'
//路由：首页|404|screen|acl(3个子路由)|product(4个子路由)|login|任意路由
//用户已经登录，不能访问login，重定位回首页
//用户未登录，只能访问login，其他的都不能法访问
//每访问一次路由页面要检验TOKEN，如果TOKEN失效要跳转到login
router.beforeEach(async (to, from, next) => {
  //进度条开始
  nprogress.start()
  const userStore = useUserStore()
  if (userStore.token) {
    try {
      //校验TOKEN合法性,并获取用户信息
      await userStore.getUserInfo()
      if (to.path === '/login') {
        next({ path: '/home' })
      }
    } catch (error) {
      ElMessage.error(error as string)
      userStore.emptyStore()
      next({ path: '/login' })
    }
  } else {
    //用户未登录
    if (to.path === '/login') {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } }) //携带想要去的路径参数，登录后可以之间转跳
    }
  }

  next()
})

router.afterEach((to, from) => {
  document.title = to.meta.title as string
  //进度条结束
  nprogress.done()
})
